package com.guli.file.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
@RequestMapping("file/download")
public class DownloadController {
    @Autowired
    HttpServletResponse response;

    /**
     * 文件下载
     * @param fileName  url 开头从组名开始
     * @throws Exception
     */
    @GetMapping("/txt")
    public void  download(String fileName) throws Exception {
        response.setContentType("application/octet-stream");//***
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="
        + URLEncoder.encode(fileName, "UTF-8"));
        // 控制输出流
        ServletOutputStream outputStream=response.getOutputStream();
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.write("文件下载测试");
        printWriter.close();
    }

    @GetMapping("/doc")
    public void  downloaddoc(String fileName) throws Exception {
        response.setContentType("application/octet-stream");//***
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="
                + URLEncoder.encode(fileName, "UTF-8"));
        // 控制输出流
        File file = new File("C:\\Users\\Y\\Desktop.doc");
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        int tmp;
        while ((tmp=fileInputStream.read())!=-1){
            outputStream.write(tmp);
        }
        outputStream.flush();
        outputStream.close();
    }


}
